/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package radiostation;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.Album;
import model.DBManager;
import model.Song;

/**
 *
 * @author sky
 */
public class GroupAlbumJFrame extends javax.swing.JFrame {

    /**
     * Creates new form GroupAlbumJFrame
     */
    public GroupAlbumJFrame() {
        em = DBManager.em;
        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        initComponents();
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        groupsAlbumQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT a FROM Album a WHERE a.artistId IS NULL");
        groupsAlbumList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(groupsAlbumQuery.getResultList());
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        newJBtn = new javax.swing.JButton();
        deleteJBtn = new javax.swing.JButton();
        editJBtn = new javax.swing.JButton();
        goHome = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("RadioStation");

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/folder-sound.png"))); // NOI18N
        jLabel1.setText("Πίνακας Άλμπουμ Συγκροτημάτων");

        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, groupsAlbumList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumId}"));
        columnBinding.setColumnName("Id");
        columnBinding.setColumnClass(Long.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumTitle}"));
        columnBinding.setColumnName("Τίτλος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumDiscnumber}"));
        columnBinding.setColumnName("Δίσκος");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumType}"));
        columnBinding.setColumnName("Τύπος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumReleaseDate}"));
        columnBinding.setColumnName("Έκδοση");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumMusicGroupId.musicGroupName}"));
        columnBinding.setColumnName("Συγκρότημα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${companyId.companyName}"));
        columnBinding.setColumnName("Δισκογραφική");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(0).setPreferredWidth(20);
            jTable1.getColumnModel().getColumn(1).setMinWidth(200);
            jTable1.getColumnModel().getColumn(2).setPreferredWidth(50);
            jTable1.getColumnModel().getColumn(3).setPreferredWidth(50);
            jTable1.getColumnModel().getColumn(4).setPreferredWidth(50);
        }

        newJBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/list-add.png"))); // NOI18N
        newJBtn.setText("Εισαγωγή");
        newJBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newJBtnActionPerformed(evt);
            }
        });

        deleteJBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/list-remove.png"))); // NOI18N
        deleteJBtn.setText("Διαγραφή");
        deleteJBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteJBtnActionPerformed(evt);
            }
        });

        editJBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/document-edit.png"))); // NOI18N
        editJBtn.setText("Μεταβολή");
        editJBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editJBtnActionPerformed(evt);
            }
        });

        goHome.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit-undo.png"))); // NOI18N
        goHome.setText("Επιστροφή στο Μενού");
        goHome.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                goHomeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(newJBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteJBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(editJBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(goHome)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newJBtn)
                    .addComponent(deleteJBtn)
                    .addComponent(editJBtn)
                    .addComponent(goHome))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void newJBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newJBtnActionPerformed
        //pat3code: spyros
        ga = new Album();
        EditGroupAlbumJFrame fga = new EditGroupAlbumJFrame(ga);
        fga.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);
        //pat3group: Listener---------------------------------
        fga.addWindowListener(new WindowListener() {
            @Override
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                if (arg0 instanceof MyWindowEvent) {
                    if (((MyWindowEvent) arg0).exitAndSave) {
                        em.persist(ga);
                        groupsAlbumList.add(ga);
                        em.getTransaction().commit();
                        em.getTransaction().begin();
                        int row = groupsAlbumList.size() - 1;
                        jTable1.setRowSelectionInterval(row, row);
                        jTable1.scrollRectToVisible(jTable1.getCellRect(row, 0, true));
                    }
                }
            }

            @Override
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }

            @Override
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }

            @Override
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
                thisFrame.setEnabled(true);
                thisFrame.requestFocus();
            }

            @Override
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }

            @Override
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }

            @Override
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
        //----------------------------------------------------
    }//GEN-LAST:event_newJBtnActionPerformed

    private void deleteJBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteJBtnActionPerformed
        // TODO add your handling code here:
        int s = jTable1.getSelectedRow();
        if (s >= 0) {
            Album a = groupsAlbumList.get(jTable1.convertRowIndexToModel(s));
            boolean inUse = false;
            for (Song song : a.getSongList()) {
                if (!song.getPlayListList().isEmpty()) {
                    inUse = true;
                    break;
                }
            }
            if (!inUse) {
                for (Song song : a.getSongList()) {
                    em.remove(song);
                }
                groupsAlbumList.remove(a);
                em.remove(a);
                em.getTransaction().commit();
                em.getTransaction().begin();
            } else {
                JOptionPane.showMessageDialog(this, "Υπάρχουν τραγούδια σε Playlist", "Προσοχή", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_deleteJBtnActionPerformed

    private void editJBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editJBtnActionPerformed
        // TODO add your handling code here:
        s = jTable1.getSelectedRow();
        //System.out.println(s);

        if (s >= 0) {
            ga = groupsAlbumList.get(s);
            //System.out.println(ga);
            EditGroupAlbumJFrame f = new EditGroupAlbumJFrame(ga);
            f.setVisible(true);
            thisFrame = this;
            thisFrame.setEnabled(false);
            //************
            f.addWindowListener(new WindowListener() {
                public void windowClosed(WindowEvent arg0) {
                    System.out.println("Window close event occur");
                    if (arg0 instanceof MyWindowEvent) {
                        if (((MyWindowEvent) arg0).exitAndSave) {
                            System.out.println(ga);
                            em.merge(ga);
                            groupsAlbumList.set(s, ga);
                            em.getTransaction().commit();
                            em.getTransaction().begin();
                        } else {
                            em.getTransaction().rollback();
                            em.getTransaction().begin();
                            java.util.Collection data = groupsAlbumQuery.getResultList();
                            for (Object entity : data) {
                                em.refresh(entity);
                            }
                            groupsAlbumList.clear();
                            groupsAlbumList.addAll(data);
                        }
                    }
                }

                public void windowActivated(WindowEvent arg0) {
                    System.out.println("Window Activated");
                }

                public void windowClosing(WindowEvent arg0) {
                    System.out.println("Window Closing");
                }

                public void windowDeactivated(WindowEvent arg0) {
                    System.out.println("Window Deactivated");
                    thisFrame.setEnabled(true);
                    thisFrame.requestFocus();
                }

                public void windowDeiconified(WindowEvent arg0) {
                    System.out.println("Window Deiconified");
                }

                public void windowIconified(WindowEvent arg0) {
                    System.out.println("Window Iconified");
                }

                public void windowOpened(WindowEvent arg0) {
                    System.out.println("Window Opened");
                }
            });
        }
    }//GEN-LAST:event_editJBtnActionPerformed

    private void goHomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goHomeActionPerformed
        // TODO add your handling code here:
        try {
            System.out.println("disposing frame");
            dispose();
        } catch (Exception e) {
            System.out.println(e);
        }
    }//GEN-LAST:event_goHomeActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // pat3group: sky Επεξεργασία με διπλό κλικ πάνω στη γραμμή του πίνακα.
        if (evt.getClickCount() > 1) {
            editJBtnActionPerformed(null);
        }
    }//GEN-LAST:event_jTable1MouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GroupAlbumJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GroupAlbumJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GroupAlbumJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GroupAlbumJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GroupAlbumJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton deleteJBtn;
    private javax.swing.JButton editJBtn;
    private javax.swing.JButton goHome;
    private java.util.List<model.Album> groupsAlbumList;
    private javax.persistence.Query groupsAlbumQuery;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton newJBtn;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    //pat3group: spyros
    EntityManager em;
    JFrame thisFrame;
    Album ga;
    int s;
       
}
